<template>
  <Modal :width="1000" v-model:visible="open" @ok="handleSuccess" title="函数宏控件">
    <BasicForm @register="registerForm" style="margin-top: 10px">
      <template #isAutoWhenList="{ model, field }">
        <div>
          <Select
            :options="isAutoWhenListOptions"
            v-model:value="model[field]"
            :get-popup-container="getPopupContainer"
            style="width: 80px"
          />
          （选是，则列表内容多时，可能会影响性能；选否，则可能因数据未实时计算出现不一致的情况）
        </div>
      </template>
      <template #paramsParams>
        <div class="flex flex-wrap justify-start">
          <div
            class="w-150px text-center p-2 cursor-pointer"
            v-for="(item, index) in [...fieldsList, ...formGetFieldsDataTo]"
            :key="index"
            @click="hanldeClick(item.value)"
            >{{ item.label }}</div
          >
        </div>
      </template>
    </BasicForm>
  </Modal>
</template>
<script setup lang="ts">
  import { ref, PropType, computed, watch, onMounted, unref, nextTick } from 'vue';
  import { Modal, message, Select } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { getVisualFormulaList } from '/@/api/formDesign/formDesign';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { useRouter } from 'vue-router';
  const { currentRoute } = useRouter();

  const emit = defineEmits(['success', 'update:visible']);
  const props = defineProps({
    visible: {
      type: Boolean as PropType<Boolean>,
      default: false,
    },
    data: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const getPopupContainer = (triggerNode) => triggerNode?.parentNode;

  const optionsList = ref<Recordable[]>([]);
  const formSchema: FormSchema[] = [
    {
      field: 'sel',
      label: '函数',
      required: true,
      component: 'Select',
      colProps: { span: 21 },
      componentProps: {
        showSearch: true,
        optionFilterProp: 'name',
        options: unref(optionsList),
        fieldNames: { label: 'name', value: 'code' },
        onChange: (e: any) => {
          console.log(e);
          const record = getFieldsValue();
          record.spanParams = optionsList.value.find((item) => item.code === e)?.params;
          record.params = record.spanParams;
          setFieldsValue({ params: record.params, spanParams: record.spanParams });
        },
      },
    },
    {
      field: 'spanParams',
      label: '形参',
      required: false,
      component: 'Input',
      colProps: { span: 21 },
      componentProps: {
        readonly: true,
      },
    },
    {
      field: 'params',
      label: '实参',
      required: false,
      component: 'Input',
      colProps: { span: 21 },
      componentProps: {
        defaultValue: '1',
      },
    },
    {
      field: 'isAutoWhenList',
      label: '列表中自动生成',
      defaultValue: true,
      required: false,
      component: 'Select',
      colProps: { span: 21 },
      slot: 'isAutoWhenList',
    },
    {
      field: 'paramsParams',
      label: '参数字段',
      required: false,
      component: 'Input',
      colProps: { span: 21 },
      slot: 'paramsParams',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, getFieldsValue }] =
    useForm({
      labelWidth: 150,
      schemas: formSchema,
      showActionButtonGroup: false,
    });

  const open = computed({
    get() {
      return props.visible;
    },
    set(e) {
      console.log('eee', e);
      emit('update:visible', e);
    },
  });
  const newData = ref<any>({});
  watch(
    () => props.data,
    async (newVal) => {
      newData.value = newVal || {};
      await nextTick();
      fetch();
    },
    {
      immediate: true,
    },
  );
  const fieldsList = ref([
    { value: 'id', label: '-ID-' },
    { value: 'cws_id', label: '-关联ID-' },
    { value: 'cws_status', label: '-记录状态-' },
    { value: 'cws_quote_id', label: '-引用记录ID-' },
    { value: 'formCode', label: '-表单编码-' },
  ]);

  const handleClose = () => {
    open.value = false;
  };

  const fetch = async () => {
    optionsList.value = await getVisualFormulaList();
    console.log('optionsList.value', optionsList.value);
    resetFields();
    updateSchema([
      {
        field: 'sel',
        componentProps: {
          options: optionsList.value,
        },
      },
    ]);
    setFieldsValue({ ...newData.value });
  };

  const formGetFieldsDataTo = ref<Recordable[]>([]);
  //获取目标字段
  const getFormGetFieldsDataTo = () => {
    try {
      const { query } = currentRoute.value;
      if (query?.formCode) {
        getFormGetFields({ formCode: query.formCode }).then((res) => {
          formGetFieldsDataTo.value = res || [];
          if (isArray(formGetFieldsDataTo.value)) {
            formGetFieldsDataTo.value.forEach((item) => {
              item.label = item.title;
              item.value = item.name;
              delete item.options;
            });
          }
        });
      }
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };
  onMounted(() => {
    getFormGetFieldsDataTo();
  });

  const handleSuccess = async () => {
    console.log('newData.value', newData.value);
    const values = await validate();
    const formdata = Object.assign({}, newData.value, values);
    console.log('formdata', formdata);
    emit('success', formdata);
    handleClose();
  };

  const hanldeClick = (value) => {
    const record = getFieldsValue();
    if (record.params) {
      record.params += value;
    } else {
      record.params = value;
    }
    setFieldsValue({ params: record.params });
  };

  const isAutoWhenListOptions = [
    {
      label: '是',
      value: true,
    },
    {
      label: '否',
      value: false,
    },
  ];
</script>
